import React, { Ref, useContext, useEffect, useRef } from 'react';
import { OneModal } from '@/components/one-ui';
import fromStyle from '@/common/pageLayout.less';
import { Form, Input, Radio, InputNumber, message } from 'antd';
import { useRequest } from '@@/plugin-request/request';
import { getCompanyID, getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import { IOneModalRef } from '@/pages/type';
import { IDictionaryTypeEdit } from '../type';
import { DictionaryContext } from '../hooks';
import { editDictionaryType } from '../service';

export const DictionaryTypeEdit: React.FC<IDictionaryTypeEdit> = ({
  onClose,
  reloadTree,
  record,
}) => {
  const [form] = Form.useForm();

  /**
   * 弹框 ref
   */
  const dictionaryModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (dictionaryModalRef) {
      if (dictionaryModalRef.current) {
        if (dictionaryModalRef.current.onModalCancel) {
          dictionaryModalRef.current.onModalCancel();
        }
      }
    }
  };

  useEffect(() => {
    form.setFieldsValue({
      ...record,
      typeName: record?.name,
    });
  }, [record]);

  const { selectKeys, reloadTableDataSource } = useContext(DictionaryContext);

  const requestEditType = useRequest(
    (params: Record<string, any>) => {
      return editDictionaryType(params);
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
        } else {
          message.error('编辑失败');
        }
        reloadTree();
        reloadTableDataSource(selectKeys?.[0]);
        // onClose();
        onCloseModal();
      },
    },
  );

  // const getTreeIcon = (flag: any) => {
  //   return (
  //     <a style={{ marginRight: 5 }}>
  //       {flag ? (
  //         <MyIcon type={'icon-ic-normal-zidianguanli'} />
  //       ) : (
  //         <MyIcon type={'icon-icon-test2'} />
  //       )}
  //     </a>
  //   );
  // };

  // const onFormValuesChange = (
  //   allValues: Record<string, any>,
  //   targetValue: Record<string, any>,
  // ) => { };

  const onOk = () => {
    form.validateFields().then((res) => {
      if (res) {
        const params = {
          seq: res?.seq,
          pID: record?.pID,
          name: res?.typeName,
          setFlow: res?.setFlow,
          tenantID: getTenantID(),
          setSubject: res?.setSubject,
          id: record?.id,
          modifyerID: getUserID(),
          modifyPositionID: getPosIDs(),
          modifyDepartmentID: getUserDepID(),
          modifyCompanyID: getCompanyID(),
          versionNum: record?.versionNum ?? 0,
        };

        requestEditType.run(params);
      }
    });
  };

  return (
    <OneModal
      open={true}
      onCancel={onClose}
      title={'编辑类型'}
      ref={dictionaryModalRef}
      onOk={onOk}
      centered={true}
      maskClosable={false}
      okButtonProps={{
        loading: requestEditType.loading,
      }}
      bodyStyle={{ padding: '5px 0px' }}
    >
      <div className={fromStyle['fromView-styles']}>
        <Form
          form={form}
        // onValuesChange={onFormValuesChange}
        >
          <Form.Item
            label={'名称'}
            name={'typeName'}
            required={true}
            rules={[
              {
                required: true,
                message: '请填写名称',
              },
            ]}
          >
            <Input placeholder={'请填写名称'} />
          </Form.Item>
          <Form.Item label={'上级类型'} name={'pName'}>
            <Input disabled placeholder="无上级类型" />
          </Form.Item>
          <Form.Item name={'setSubject'} label={'科目设置'} initialValue={0}>
            <Radio.Group
              options={[
                {
                  value: 0,
                  label: '未设置',
                },
                {
                  value: 1,
                  label: '设为科目',
                },
              ]}
            />
          </Form.Item>
          <Form.Item name="setFlow" label={'流程设置'} initialValue={0}>
            <Radio.Group
              options={[
                {
                  value: 0,
                  label: '未设置',
                },
                {
                  value: 1,
                  label: '流程类别',
                },
                {
                  value: 2,
                  label: '流程状态',
                },
              ]}
            />
          </Form.Item>
          <Form.Item
            name="seq"
            label={'排序'}
            initialValue={1}
            required={true}
            rules={[
              {
                message: '请输入正整数！',
                pattern: new RegExp('^[0-9][0-9]*$'),
              },
            ]}
          >
            <InputNumber placeholder={'请输入排序'} min={0} />
          </Form.Item>
        </Form>
      </div>
    </OneModal>
  );
};
